package edu.zjucst.spb.util;

import edu.zjucst.spb.domain.ResponseResult;
import edu.zjucst.spb.enums.OptStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Slf4j
public class FileUtil {
    private static final String[] suffixs = new String[]{};
    public static boolean upload(MultipartFile file, String path) throws IOException {
        if (!verifyFile(file, path)) {
            return false;
        }
        if (!file.isEmpty()) {
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            File filePath = new File(path);

            System.out.println(filePath);
            //如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                log.info("mkdirs: {}", filePath.getParentFile());
                filePath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
        }
        return true;
    }
    public static ResponseEntity<byte[]> getResponseEntity(String fileName, String path) throws IOException {
        //构建将要下载的文件对象
        File file = new File(path);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        //通知浏览器以下载方式(attachment)打开文件
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //定义以二进制流数据(最常见的文件下载)的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //使用spring mvc框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);

    }
    public static boolean verifyFile(MultipartFile file, String path) {
//        SuffixFileFilter suffixFileFilter = new SuffixFileFilter(suffixs);
//        if (!suffixFileFilter.accept(new File(path + file.getOriginalFilename()))) {
//            return false;
//        }
        return true;
    }

}
